package com.dangf.hz.service;

import java.util.Map;

import pw.hais.uitl.DES;

import com.dangf.hz.dao.UserDao;
import com.dangf.hz.entity.User;


/**
 * 用户 业务逻辑层
 * @author Hello_海生
 * @date 2014年7月30日
 */
public class UserService extends BaseService{
	private UserDao userDao;	
	public UserService(){
		userDao = new UserDao();
	}
	
	/**
	 * 登录方法
	 * @param u
	 * @return
	 */
	public Map<String,Object> login(User u){
		User user = userDao.findUserByUserName(u.getUsername());
		if(user==null){
			return setResult("301", "用户不存在！", "");
		}else if(!u.getPassword().equals(user.getPassword())){
			return setResult("301", "密码错误！", "");
		}else{
			user.setToken(DES.encrypt(user.getId()+"@--@"+user.getUsername()+"@--@"+user.getPassword()));
			userDao.update(user, "id='"+user.getId()+"'");
			user.setPassword("");
			
			return setResult("200", "登陆成功！",user);
		}
	}

	/**
	 * 注册账号
	 * @param u
	 * @return
	 */
	public Map<String, Object> save(User u) {
		User user = userDao.findUserByUserName(u.getUsername());
		if(user==null){
			if(userDao.save(u)){
				return setResult("301", "注册成功，请到登录页登录！！", u);
			}else{
				return setResult("500", "注册失败，系统错误！！", "");
			}
		}else{
			return setResult("301", "注册失败，账号已存在！", "");
		}

	}


	/**
	 * 查询信息
	 * @param u
	 * @return
	 */
	public Map<String, Object> show(User u) {
		User user = userDao.findEntityById(u.getId()+"");

		if(user!=null){
			if(!"".equals(u.getToken()) && u.getToken().equals(user.getToken())){
				return setResult("200", "查询个人信息成功！", user);
			}else{
				user.setPassword("");
				user.setToken("");
				return setResult("200", "查询"+user.getUsername()+"信息成功！", user);
			}
		}else{
			return setResult("301", "查询失败，该人不存在！", "");
		}
		
	}


	/**
	 * 修改用户信息
	 * @param u
	 * @return
	 */
	public Map<String, Object> update(User u) {
		User user = userDao.findEntityById(u.getId()+"");
		
		if(u.getToken().equals(user.getToken())){
			if(!"".equals(u.getPassword()))user.setPassword(u.getPassword());
			if(!"".equals(u.getEmail()))user.setEmail(u.getEmail());
			if(!"".equals(u.getPhoto()))user.setPhoto(u.getPhoto());
			int rs = userDao.update(user, " id = '"+u.getId()+"'");
			if(rs!=0){
				return setResult("200", "用户信息修改成功！", user);
			}else{
				return setResult("500", "修改失败，系统出错！", "");
			}
		}else{
			return setResult("301", "身份验证出错，不能修改！", "");
		}
	}

}
